import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import {
  Row, Col, Spin, Modal, Button, message, Popover
} from 'antd';
import withDragDropContext from 'components/with-dnd-context';
import 'styles/components/template/drag-widget-page/drag-widget-page.scss';
import formService from 'containers/setting/form/form.service';
import DragWidgetItem from 'containers/setting/form/form-detail/form-detail-custom/drag-source/drag-widget-item';
import FakeDropLayout from 'containers/setting/form/form-detail/form-detail-custom/drop-source/fake-drop-layout';
import PhoneContent from 'containers/setting/form/form-detail/form-detail-custom/drop-source/phone-content';
import WidgetSetting from 'components/template/widget/widget-setting';
import IPhoneX from 'components/iphone-x';
import QrCode from "qrcode.react";

const {confirm} = Modal;

class FormDetailCustom extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      normalWidget: [],
      combineWidget: [],
      nowWidget: [],
      nowSelectedIndex: -1,
      counter: 0,
      loading: false,
      saving: false,
      previewing: false,
      formDescriptionWidget: {},
      reportScopeList: [], // 报表属性可选范围
      adjustScopeList: [], // 参与核算可选范围
      qrcodeValue: ''
    };
    this.timeCount = 0;
  }

  componentWillMount() {
    const { form, propertyList } = this.context;
    const nowWidget = JSON.parse(JSON.stringify(form.customFormFields));
    let participantsIndex = -1;
    let outIndex = -1;
    let payeeIndex = -1; // 收款方
    let bankAccountIndex = -1; // 银行卡账号
    let fatherCostCenterIndex = -1; // 父成本中心
    let sonCostCenterIndex = -1; // 子成本中心
    // counterFlag为内部组件排序所需key值，在此处初始化
    nowWidget.map((widget, index) => {
      // widget.counterFlag = index;
      // 内部参与人控件需要检测out_participant_num/out_participant_name控件，
      // 因为内部参与人控件包含了两个组件
      // 所以为了符合widget控件的设计思路，现在数组里删除，保存的时候再进行添加
      if (widget.messageKey === 'out_participant_num' || widget.messageKey === 'out_participant_name') {
        outIndex = index;
      }
      if (widget.messageKey === 'select_participant') {
        participantsIndex = index;
      }
      // 联动开关要用
      if (!widget.customFormFieldI18nDTOS || widget.customFormFieldI18nDTOS.length === 0) {
        widget.customFormFieldI18nDTOS = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            fieldName: widget.fieldName,
            promptInfo: widget.promptInfo,
            language: language.code
          };
          widget.customFormFieldI18nDTOS.push(i18nDTO);
        });
      }

      if (!widget.i18n) {
        widget.i18n = {};
      }
      if (!widget.i18n.fieldName || !widget.i18n.fieldName.length) {
        const fieldNameI18n = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            language: language.code,
            value: widget.fieldName ? widget.fieldName : ''
          };
          fieldNameI18n.push(i18nDTO);
        });
        widget.i18n.fieldName = fieldNameI18n;
      }

      if (!widget.i18n.promptInfo || !widget.i18n.promptInfo.length) {
        const promptInfoI18n = [];
        this.props.languageList.map((language) => {
          const i18nDTO = {
            language: language.code,
            value: widget.promptInfo ? widget.promptInfo : ''
          };
          promptInfoI18n.push(i18nDTO);
        });
        widget.i18n.promptInfo = promptInfoI18n;
      }

      if (widget.messageKey === 'linkage_switch') {
        widget.customFormFieldI18nDTOS && widget.customFormFieldI18nDTOS.map((i18nDTO) => {
          if (widget.i18n.fieldContent) {
            widget.i18n.fieldContent.map((oneContent) => {
              if (oneContent.language.toLowerCase() === i18nDTO.language.toLowerCase()) {
                i18nDTO.fieldContent = oneContent.value;
              }
            });
          }
        });
      }

      return widget;
    });
    if (outIndex > -1 && participantsIndex > -1) {
      const participantsWidget = nowWidget[participantsIndex];
      const outWidget = nowWidget[outIndex];
      participantsWidget.outFieldName = outWidget.fieldName;
      participantsWidget.outPromptInfo = outWidget.promptInfo;
      participantsWidget.outRequired = outWidget.required;
      participantsWidget.outFieldCode = outWidget.fieldCode;
      participantsWidget.outFieldOID = outWidget.fieldOID;
      participantsWidget.outID = outWidget.id;
      participantsWidget.outMessageKey = outWidget.messageKey;
      participantsWidget.outCustomFormFieldI18nDTOS = outWidget.customFormFieldI18nDTOS;
      participantsWidget.outI18n = outWidget.i18n;
      nowWidget.splice(outIndex, 1);
    }
    // splice out_participant_num这个控件后index会发生变化，此处收款方和参与人要分开处理
    nowWidget.map((widget, index) => {
      // 收款方控件需要检测contact_bank_account控件，
      // 因为收款方控件包含了两个组件
      // 所以为了符合widget控件的设计思路，现在数组里删除，保存的时候再进行添加
      if (widget.messageKey === 'payee') {
        payeeIndex = index;
      }
      if (widget.messageKey === 'contact_bank_account') {
        bankAccountIndex = index;
      }
    });
    if (payeeIndex > -1 && bankAccountIndex > -1) {
      const payeeWidget = nowWidget[payeeIndex];
      const bankAccountWidget = nowWidget[bankAccountIndex];
      payeeWidget.bankFieldName = bankAccountWidget.fieldName;
      payeeWidget.bankPromptInfo = bankAccountWidget.promptInfo;
      payeeWidget.bankFieldCode = bankAccountWidget.fieldCode;
      payeeWidget.bankFieldOID = bankAccountWidget.fieldOID;
      payeeWidget.bankID = bankAccountWidget.id;
      payeeWidget.bankCustomFormFieldI18nDTOS = bankAccountWidget.customFormFieldI18nDTOS;
      payeeWidget.bankI18n = bankAccountWidget.i18n;
      nowWidget.splice(bankAccountIndex, 1);
    }
    // 级联成本中心控件的处理
    nowWidget.map((widget, index) => {
      // 级联成本中心控件需要检测select_cost_center控件，
      // 把两个有级联关系的select_cost_center控件拼装成一个linkage_cost_center控件
      if (widget.messageKey === 'select_cost_center') {
        const dataSource = widget.dataSource ? JSON.parse(widget.dataSource) : '';
        if (dataSource.type === 'father') {
          fatherCostCenterIndex = index;
        }
        if (dataSource.type === 'son') {
          sonCostCenterIndex = index;
        }
      }
    });
    if (fatherCostCenterIndex > -1 && sonCostCenterIndex > -1) {
      const fatherWidget = nowWidget[fatherCostCenterIndex];
      const sonWidget = nowWidget[sonCostCenterIndex];
      const subCostCenterOID = JSON.parse(sonWidget.dataSource).costCenterOID;
      const dataSource = JSON.parse(fatherWidget.dataSource);
      const subFieldConstraint = sonWidget.fieldConstraint ? JSON.parse(sonWidget.fieldConstraint) : {};
      dataSource.subCostCenterOID = subCostCenterOID;
      fatherWidget.dataSource = JSON.stringify(dataSource);
      fatherWidget.subFieldName = sonWidget.fieldName;
      fatherWidget.subPromptInfo = sonWidget.promptInfo;
      fatherWidget.subFieldCode = sonWidget.fieldCode;
      fatherWidget.subFieldOID = sonWidget.fieldOID;
      fatherWidget.subLedEnabled = sonWidget.ledEnabled;
      fatherWidget.subLedOrmKey = sonWidget.ledOrmKey;
      fatherWidget.subID = sonWidget.id;
      fatherWidget.subCustomFormFieldI18nDTOS = sonWidget.customFormFieldI18nDTOS;
      fatherWidget.subI18n = sonWidget.i18n;
      fatherWidget.messageKey = 'linkage_cost_center';
      fatherWidget.subWithCode = subFieldConstraint.withCode;
      nowWidget.splice(sonCostCenterIndex, 1);
    }
    // counterFlag为内部组件排序所需key值，在此处初始化
    // 要等前面参与人，收款方，级联成本中心控件处理完毕后初始化
    nowWidget.map((widget, index) => {
      widget.counterFlag = index;
    });
    // 表单内description控件，不可删除不可拖拽
    let formDescriptionWidget = {
      messageKey: 'form.description',
      title: '',
      content: ''
    };
    this.props.languageList.map((language) => {
      formDescriptionWidget[language.code.toLowerCase()] = {
        title: '',
        content: ''
      };
    });
    propertyList && propertyList.map((property) => {
      if (property.propertyName === 'form.description') {
        if (property.propertyValue) {
          formDescriptionWidget = JSON.parse(property.propertyValue);
          formDescriptionWidget.messageKey = 'form.description';
          if (formDescriptionWidget[this.props.user.language.toLowerCase()]) {
            const nowInfo = formDescriptionWidget[this.props.user.language.toLowerCase()];
            formDescriptionWidget.title = nowInfo.title;
            formDescriptionWidget.content = nowInfo.content;
          } else {
            formDescriptionWidget.title = '';
            formDescriptionWidget.content = '';
          }
        }
      }
      if (property.propertyName === 'application.participants.import.scope') {
        nowWidget.map((widget) => {
          if (widget.messageKey === 'select_participant') {
            let editable = true;
            let temp = {};
            if (widget.fieldContent) {
              temp = JSON.parse(widget.fieldContent);
              editable = temp.editable;
            }
            widget.participantsImportScope = editable ? property.propertyValue : '99';
            return widget;
          }
        });
      }
    });
    this.setState({ nowWidget, counter: nowWidget.length, formDescriptionWidget });
    this.getWidgetList();
    this.getReportScope();
    this.checkAdjustScope();
  }

  getWidgetList = () => {
    const { formType, formOID } = this.context;
    if (formType) {
      this.setState({ loading: true });
      Promise.all([formService.getWidgetList(formType, 1001, formOID), formService.getWidgetList(formType, 1002, formOID)]).then((res) => {
        res[0].data.map((item) => {
          item.fieldConstraint = item.constraintRule;
          item.readonly = !item.deleted;
        });
        res[1].data.map((item) => {
          item.fieldConstraint = item.constraintRule;
          item.readonly = !item.deleted;
        });
        const normalWidget = [];
        res[0].data.map((item) => {
          // 老公司只显示法人控件新公司显示公司控件
          if (this.props.isOldCompany) {
            if (item.messageKey != 'select_company') {
              normalWidget.push(item);
            }
          } else if (item.messageKey != 'select_corporation_entity') normalWidget.push(item);
        });
        this.setState({ normalWidget, combineWidget: res[1].data, loading: false }, () => {
          this.processWidget();
        });
      });
    }
  };

  // 处理控件是否可删除
  processWidget = () => {
    const { normalWidget, combineWidget, nowWidget } = this.state;
    nowWidget.map((widget) => {
      normalWidget.map((norWidget) => {
        if (widget.messageKey === norWidget.messageKey) {
          widget.readonly = norWidget.readonly;
        }
      });
      combineWidget.map((combWidget) => {
        if (widget.messageKey === combWidget.messageKey) {
          widget.readonly = combWidget.readonly;
        }
      });
    });
    this.setState({nowWidget});
  };

  getReportScope = () => {
    formService.getExpenseReportScope(4003).then((resp) => {
      const reportScopeList = [];
      if (resp.data && resp.data.length) {
        resp.data.map((item) => {
          if (item.enabled) {
            reportScopeList.push(item);
          }
        });
      }
      this.setState({
        reportScopeList
      });
    }).catch((error) => {
      message.error(messages('common.error'));
    });
  };

  checkAdjustScope = () => {
    formService.isHasAdjustScope().then((res) => {
      if (res.data) {
        this.getAdjustScope();
      }
    });
  };

  getAdjustScope = () => {
    const { form } = this.context;
    formService.getAdjustScope(form.setOfBooksId, form.entityType).then((resp) => {
      if (resp.data && resp.data.length) {
        this.setState({
          adjustScopeList: resp.data
        });
      }
    }).catch((error) => {
      message.error(messages('common.error'));
    });
  };

  /**
   * 从列表中把widget拖拽入phone-content时的事件
   * @param widget 拖入的widget
   * @param index 拖入后的index
   */
  handleDrop = (widget, index) => {
    let { nowWidget, counter } = this.state;
    // 因为city控件为新的地点控件，老的destination控件不再允许拖入了
    if (widget.messageKey === 'destination') {
      message.error(messages('setting.key2211')/* 该控件已禁用，请使用城市控件。 */);
      return;
    }
    if (widget.maxAmount === 0) {
      message.error(messages('setting.key1456', {arg1: widget.maxAmount}/* 该控件只能有{arg1}个 */));// 该控件只能有${widget.maxAmount}个
      return;
    }
    if (widget.maxAmount) {
      let count = 0;
      nowWidget.map((item) => {
        item.messageKey === widget.messageKey && count++;
      });
      if (count >= widget.maxAmount) {
        message.error(messages('setting.key1456', {arg1: widget.maxAmount}/* 该控件只能有{arg1}个 */));// 该控件只能有${widget.maxAmount}个
        return;
      }
    }
    // 收款方控件和银行卡号控件不能同时存在于一个表单上
    let payeeIndex = -1;
    let bankAccountIndex = -1;
    nowWidget.map((singleWidget, index) => {
      if (singleWidget.messageKey === 'payee') {
        payeeIndex = index;
      }
      if (singleWidget.messageKey === 'contact_bank_account') {
        bankAccountIndex = index;
      }
    });

    if (
      (payeeIndex > -1 && widget.messageKey === 'contact_bank_account')
      || (bankAccountIndex > -1 && widget.messageKey === 'payee')
    ) {
      message.error(messages('setting.key2183')/* 添加失败：银行账号控件、收款方控件不可同时使用 */);
      return;
    }
    const tempWidget = JSON.parse(JSON.stringify(widget));
    // 因为ListSort根据key值排序，key值不能改变和重复，所以此处给每一个拖拽进入的组件一个counter计数为counterFlag
    tempWidget.counterFlag = counter++;
    tempWidget.fieldName = tempWidget.name;
    nowWidget.splice(index, 0, tempWidget);
    this.setState({ nowWidget, counter, nowSelectedIndex: index });
  };

  /**
   * 选择某一组件时的回调
   * @param nowSelectedIndex  列表中的第几个
   * @param widget  对应widget对象
   */
  handleSelectWidget = (nowSelectedIndex, widget) => {
    this.setState({ nowSelectedIndex });
  };

  /**
   * phone-content内部排序后的事件
   * @param result 返回的ReactDom，key值为拖拽进入时定义的counterFlag
   */
  handleSort = (result) => {
    const { nowWidget, nowSelectedIndex } = this.state;
    // 记录当前选择的counterFlag
    const nowSelectWidgetCounter = nowWidget[nowSelectedIndex].counterFlag;
    let targetIndex = -1;
    const tempWidget = [];
    // 根据排序后的key值排序
    result.map((item) => {
      nowWidget.map((widget) => {
        (`${widget.counterFlag}`) === item.key && tempWidget.push(widget);
      });
    });
    // 寻找之前选择的index
    tempWidget.map((item, index) => {
      if (item.counterFlag === nowSelectWidgetCounter) targetIndex = index;
    });
    this.setState({ nowWidget: tempWidget, nowSelectedIndex: targetIndex });
  };

  /**
   * phone-content内部删除后的事件
   * @param index 待删除的索引
   */
  handleDelete = (index) => {
    let { nowWidget, nowSelectedIndex } = this.state;
    confirm({
      title: messages('setting.key616'/* 你确定要删除这个组件吗? */), // 你确定要删除这个组件吗?
      content: messages('setting.key617'/* 配置项将不会保存 */), // 配置项将不会保存
      okType: 'danger',
      okText: messages('common.delete'), // 删除
      cancelText: messages('common.cancel'), // 取消
      onOk: () => {
        nowWidget.splice(index, 1);
        nowSelectedIndex = -1;
        this.setState({ nowWidget, nowSelectedIndex });
      }
    });
  };

  /**
   * 更改widget属性的回调
   * @param widget
   */
  handleChangeWidget = (widget) => {
    if (widget.messageKey === 'form.description') {
      const formDescriptionWidget = {};
      widget.titleI18n.map((i18n) => {
        if (!formDescriptionWidget[i18n.language]) formDescriptionWidget[i18n.language] = {};
        formDescriptionWidget[i18n.language].title = i18n.value;
      });
      widget.contentI18n.map((i18n) => {
        if (!formDescriptionWidget[i18n.language]) formDescriptionWidget[i18n.language] = {};
        formDescriptionWidget[i18n.language].content = i18n.value;
      });
      formDescriptionWidget.enable = widget.enable;
      formDescriptionWidget.messageKey = 'form.description';
      let nowInfo = {};
      if (formDescriptionWidget[this.props.user.language.toLowerCase()]) {
        nowInfo = formDescriptionWidget[this.props.user.language.toLowerCase()];
      } else {
        nowInfo = {title: '', content: ''};
      }
      formDescriptionWidget.title = nowInfo.title;
      formDescriptionWidget.content = nowInfo.content;
      this.setState({ formDescriptionWidget });
    } else {
      const { nowWidget, nowSelectedIndex } = this.state;
      nowWidget[nowSelectedIndex] = widget;
      this.setState({ nowWidget });
    }
  };

  handleFormData = () => {
    const { formDescriptionWidget, nowWidget } = this.state;
    const { form: originalForm } = this.context;
    const { language: currentLanguage, languageList } = this.props;
    const form = JSON.parse(JSON.stringify(originalForm)); // 去除context中form的对象引用，在保存成功后刷新context的form
    // 组装说明文字
    const formDescriptionData = {};
    formDescriptionData.formOID = form.formOID;
    formDescriptionData.propertyName = 'form.description';
    const descriptionValue = {};
    descriptionValue.enable = formDescriptionWidget.enable;
    Object.keys(formDescriptionWidget).map((key) => {
      languageList.map((language) => {
        if (key === language.code.toLowerCase()) {
          descriptionValue[key] = formDescriptionWidget[key];
        }
      });
    });
    formDescriptionData.propertyValue = JSON.stringify(descriptionValue);
    const targetWidgets = [].concat(JSON.parse(JSON.stringify(nowWidget)));
    targetWidgets.map((widget, index) => {
      if (widget.messageKey === 'select_participant' && widget.fieldContent
        && JSON.parse(widget.fieldContent).out) {
        const newWidget = {};
        newWidget.isTipsShow = widget.isTipsShow || false;
        newWidget.fieldTips = widget.fieldTips;
        newWidget.messageKey = widget.outMessageKey ? widget.outMessageKey : 'out_participant_num';
        newWidget.fieldName = widget.outFieldName;
        newWidget.promptInfo = widget.outPromptInfo;
        newWidget.required = widget.outRequired;
        newWidget.isReadOnly = widget.outIsReadOnly;
        newWidget.isPDFShow = widget.outIsPDFShow;
        newWidget.id = widget.outID;
        newWidget.fieldCode = widget.outFieldCode;
        newWidget.fieldOID = widget.outFieldOID;
        newWidget.fieldConstraint = "";
        newWidget.i18n = widget.outI18n;
        newWidget.fieldNameI18n = widget.outFieldNameI18n;
        newWidget.promptInfoI18n = widget.outPromptInfoI18n;
        newWidget.valid = true;
        newWidget.dataSource = "";
        newWidget.fieldType = "LONG";
        targetWidgets.splice(index + 1, 0, newWidget);
      }
    });
    targetWidgets.map((widget, index) => {
      if (widget.messageKey === 'payee') {
        const newWidget = {};
        newWidget.isTipsShow = widget.isTipsShow || false;
        newWidget.fieldTips = widget.fieldTips;
        newWidget.messageKey = 'contact_bank_account';
        newWidget.fieldName = widget.bankFieldName;
        newWidget.promptInfo = widget.bankPromptInfo;
        newWidget.required = widget.required;
        newWidget.isReadOnly = widget.isReadOnly;
        newWidget.isPDFShow = widget.isPDFShow;
        newWidget.id = widget.bankID;
        newWidget.fieldCode = widget.bankFieldCode;
        newWidget.fieldOID = widget.bankFieldOID;
        newWidget.fieldConstraint = "";
        newWidget.i18n = widget.bankI18n;
        newWidget.fieldNameI18n = widget.bankFieldNameI18n;
        newWidget.promptInfoI18n = widget.bankPromptInfoI18n;
        newWidget.valid = true;
        newWidget.dataSource = "";
        newWidget.fieldType = "TEXT";
        targetWidgets.splice(index + 1, 0, newWidget);
      }
    });
    targetWidgets.map((widget, index) => {
      if (widget.messageKey === 'linkage_cost_center') {
        widget.messageKey = 'select_cost_center';
        widget.originMessageKey = 'linkage_cost_center';
        const fieldContent = [];
        fieldContent.push({
          fieldNameI18n: widget.subFieldNameI18n,
          promptInfoI18n: widget.subPromptInfoI18n
        });
        widget.fieldContent = JSON.stringify(fieldContent);
        const dataSource = widget.dataSource ? JSON.parse(widget.dataSource) : '';
        if (dataSource.costCenterOID) {
          widget.dataSource = JSON.stringify({costCenterOID: dataSource.costCenterOID, type: 'father'});// father标记为父成本中心
        } else {
          widget.dataSource = "";
        }
        const fieldConstraint = widget.fieldConstraint ? JSON.parse(widget.fieldConstraint) : {};
        const {isApportionItem} = fieldConstraint;
        fieldConstraint.withoutDefaultValue = !fieldConstraint.withDefaultValue;
        widget.fieldConstraint = JSON.stringify(fieldConstraint);
        widget.fieldType = 'TEXT';
        const newWidget = {};
        newWidget.isTipsShow = widget.isTipsShow || false;
        newWidget.fieldTips = widget.fieldTips;
        newWidget.messageKey = 'select_cost_center';
        newWidget.originMessageKey = 'linkage_cost_center';
        newWidget.fieldName = widget.subFieldName;
        newWidget.promptInfo = widget.subPromptInfo;
        newWidget.required = widget.required;
        newWidget.isReadOnly = widget.isReadOnly;
        newWidget.isPDFShow = widget.isPDFShow;
        newWidget.ledEnabled = widget.subLedEnabled;
        newWidget.ledOrmKey = widget.subLedOrmKey;
        newWidget.id = widget.subID;
        newWidget.fieldCode = widget.subFieldCode;
        newWidget.fieldOID = widget.subFieldOID;
        newWidget.fieldConstraint = JSON.stringify({isApportionItem, withoutDefaultValue: true, withCode: widget.subWithCode});
        newWidget.i18n = {};
        newWidget.fieldNameI18n = widget.subFieldNameI18n;
        newWidget.promptInfoI18n = widget.subPromptInfoI18n;
        newWidget.valid = true;
        if (dataSource.subCostCenterOID) {
          newWidget.dataSource = JSON.stringify({costCenterOID: dataSource.subCostCenterOID, type: 'son'});// son标记为子成本中心
        } else {
          newWidget.dataSource = "";
        }
        newWidget.fieldType = "TEXT";
        targetWidgets.splice(index + 1, 0, newWidget);
      }
    });
    // 组装表单控件
    let participantsImportScopeData = null;
    targetWidgets.map((widget, index) => {
      if (widget.messageKey === 'select_participant') {
        participantsImportScopeData = {
          formOID: form.formOID,
          propertyName: 'application.participants.import.scope',
          propertyOther: null,
          propertyValue: widget.participantsImportScope
        };
        let editable = true;
        let temp = {};
        if (widget.fieldContent) {
          temp = JSON.parse(widget.fieldContent);
          editable = temp.editable;
        }
        if (widget.participantsImportScope) {
          participantsImportScopeData.propertyValue = editable ? widget.participantsImportScope : '1';
        } else {
          participantsImportScopeData.propertyValue = '1';
        }
      }

      if (!widget.i18n) {
        widget.i18n = {};
      }

      if (widget.fieldNameI18n) {
        widget.i18n.fieldName = widget.fieldNameI18n;
      }
      if (widget.promptInfoI18n) {
        widget.i18n.promptInfo = widget.promptInfoI18n;
      }

      widget.sequence = index;

      if (widget.messageKey === 'linkage_switch') {
        widget.i18n.fieldContent = [];
        widget.customFormFieldI18nDTOS.map((i18nDTO) => {
          widget.i18n.fieldContent.push({
            language: i18nDTO.language,
            value: i18nDTO.fieldContent
          });
        });
      }
      if (widget.messageKey === 'select_box') {
        const temp = JSON.parse(widget.fieldContent);
        temp.length && temp.map((box) => {
          if (!box.nameI18n) {
            box.nameI18n = [];
            languageList.map((language) => {
              box.nameI18n.push({
                language: language.code.toLowerCase(),
                value: currentLanguage.code.toLowerCase() === language.code.toLowerCase() ? box.name : ''
              });
            });
          }
        });
        widget.i18n.fieldContent = [];
        languageList.map((language) => {
          const mappingFieldContent = JSON.parse(JSON.stringify(temp));
          mappingFieldContent.map((box) => {
            box.nameI18n.map((subLanguage) => {
              if (subLanguage.language === language.code.toLowerCase()) {
                box.name = subLanguage.value;
              }
            });
          });
          widget.i18n.fieldContent.push({
            language: language.code,
            value: JSON.stringify(mappingFieldContent)
          });
        });
        widget.fieldContent = JSON.stringify(temp);
      }
      if (widget.messageKey === 'number') {
        const temp = widget.fieldContent ? JSON.parse(widget.fieldContent) : {unit: ''};
        if (!temp.unitI18n) {
          temp.unitI18n = [];
          languageList.map((language) => {
            temp.unitI18n.push({
              language: language.code.toLowerCase(),
              value: currentLanguage.code.toLowerCase() === language.code.toLowerCase() ? temp.unit : ''
            });
          });
        }
        widget.i18n.fieldContent = [];
        languageList.map((language) => {
          const mappingFieldContent = JSON.parse(JSON.stringify(temp));
          mappingFieldContent.unitI18n.map((subLanguage) => {
            if (subLanguage.language === language.code.toLowerCase()) {
              mappingFieldContent.unit = subLanguage.value;
            }
          });
          widget.i18n.fieldContent.push({
            language: language.code,
            value: JSON.stringify(mappingFieldContent)
          });
        });
        widget.fieldContent = JSON.stringify(temp);
      }
      if (widget.messageKey === 'start_date' || widget.messageKey === 'end_date') {
        if (widget.fieldConstraint) {
          const temp = JSON.parse(widget.fieldConstraint);
          if (temp.enableTime === false) {
            temp.defaultTime = null;
          }
          widget.fieldConstraint = JSON.stringify(temp);
        }
      }
      if (widget.messageKey === 'prompt_key') {
        widget.fieldName = '';
        widget.i18n.fieldName = [];
      }
      return widget;
    });
    form.customFormFields = targetWidgets;
    const savePropertyList = [];
    savePropertyList.push(formDescriptionData);
    participantsImportScopeData && savePropertyList.push(participantsImportScopeData);
    return {form, savePropertyList};
  };

  // 保存表单
  handleSave = () => {
    const { form, savePropertyList } = this.handleFormData();

    if (!this.validateData(form)) {
      return;
    }

    this.setState({ saving: true });
    const serviceArray = [
      formService.saveFormProperty(savePropertyList),
      formService.saveFormDetail(form)
    ];
    Promise.all(serviceArray).then((res) => {
      message.success(messages('common.save.success', {name: form.formName}));
      this.refreshForm(form);
      this.setState({ saving: false });
    }).catch((e) => {
      const error = e.response.data;
      if (error.validationErrors && error.validationErrors.length) {
        message.error(`${messages('common.save.filed')}，${error.validationErrors[0].message}`);
      } else {
        message.error(`${messages('common.save.filed')}，${error.message}`);
      }
      this.setState({ saving: false });
    });
  };

  // 保存成功后更新context里的form
  refreshForm = (newFormData) => {
    const { form } = this.context;
    form.customFormFields = JSON.parse(JSON.stringify(newFormData.customFormFields));
  };

  // 是否包含某种类型的控件
  isHasSpecialField = (messageKey) => {
    const { nowWidget } = this.state;
    let isHas = false;
    nowWidget.map((widget) => {
      if (messageKey === widget.messageKey) {
        isHas = true;
      }
    });
    return isHas;
  };

  // 定位到报错的控件
  handleErrorIndex = (messageKey) => {
    const { nowWidget } = this.state;
    let errorIndex = -1;
    if (messageKey === 'out_participant_num') {
      errorIndex = this.handleErrorIndex('select_participant');
    } else if (messageKey === 'contact_bank_account' && this.isHasSpecialField('payee')) {
      errorIndex = this.handleErrorIndex('payee');
    } else {
      nowWidget.map((widget, index) => {
        if (messageKey === widget.messageKey) {
          errorIndex = index;
        }
      });
    }
    return errorIndex;
  };

  // 根据messageKey查询控件可配置的最大数量
  getMaxAmount = (messageKey) => {
    const { normalWidget, combineWidget } = this.state;
    const allWidgetList = JSON.parse(JSON.stringify(normalWidget.concat(combineWidget)));
    let maxAmount = null;
    allWidgetList.map((widget, index) => {
      if (messageKey === widget.messageKey) {
        maxAmount = widget.maxAmount ? widget.maxAmount : null;
      }
    });
    return maxAmount;
  };

  // 保存，提交前数据校验
  validateData = (form) => {
    let isOk = true;
    let errorMsg = '';
    let errorMessageKey = '';
    let errorIndex = -1;
    let startEndDateNum = 0; // 开始结束日期控件合计数量 在报销单中需要成对出现
    let costCenterNum = 0;// 成本中心控件的数量
    const costCenterMaxAmount = this.getMaxAmount('select_cost_center');
    const costCenterOIDList = [];
    form.customFormFields.map((customFormField) => {
      if (!customFormField.fieldName && customFormField.messageKey !== 'prompt_key') {
        errorMsg = messages('setting.key618'/* 标题不能为空 */);// 标题不能为空
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if (!customFormField.promptInfo && customFormField.messageKey === 'prompt_key') {
        errorMsg = messages('setting.key2223')/* 提示文字不能为空 */;
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if (customFormField.reportShow && !customFormField.reportOrmKey) {
        errorMsg = messages('setting.key1457', {arg1: customFormField.fieldName}/* 请选择{arg1}代入报表的属性 */);// 请选择${customFormField.fieldName}代入报表的属性
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if (customFormField.ledEnabled && !customFormField.ledOrmKey) {
        errorMsg = messages('setting.key1853', {arg1: customFormField.fieldName})/* 请选择{arg1}参与核算的字段 */;
        errorMessageKey = customFormField.originMessageKey ? customFormField.originMessageKey : customFormField.messageKey;
        isOk = false;
      }
      if (customFormField.messageKey === 'employee_expand' && customFormField.dataSource === '') {
        errorMsg = messages('setting.key1458', {arg1: customFormField.fieldName}/* 请选择{arg1}扩展字段选项 */);// 请选择${customFormField.fieldName}扩展字段选项
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if ((customFormField.messageKey === 'cust_list' || customFormField.messageKey === 'more_cust_list') && customFormField.dataSource === '') {
        errorMsg = `${customFormField.fieldName}${messages('setting.key619'/* 选择列表不能为空 */)}`;
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if (customFormField.messageKey === 'select_cost_center') {
        costCenterNum++;
        if (customFormField.dataSource) {
          const {costCenterOID} = JSON.parse(customFormField.dataSource);
          if (costCenterOIDList.indexOf(costCenterOID) > -1) {
            errorMsg = messages('setting.key1655')/* 存在重复的成本中心 */;
            errorMessageKey = 'linkage_cost_center';
            isOk = false;
          }
          costCenterOIDList.push(costCenterOID);
        }
      }
      if (customFormField.messageKey === 'select_cost_center' && customFormField.dataSource === '') {
        errorMsg = messages('setting.key1459', {arg1: customFormField.fieldName}/* {arg1}成本中心列表不可为空 */);// ${customFormField.fieldName}成本中心列表不可为空
        errorMessageKey = customFormField.originMessageKey ? customFormField.originMessageKey : customFormField.messageKey;
        isOk = false;
      }
      if (customFormField.messageKey === 'select_box') {
        JSON.parse(customFormField.fieldContent).map((item) => {
          if (!item.name || item.name === '') {
            errorMsg = messages('setting.key1460', {arg1: customFormField.fieldName}/* {arg1}选项名称不能为空 */);// ${customFormField.fieldName}选项名称不能为空
            errorMessageKey = customFormField.messageKey;
            isOk = false;
          }
        });
      }
      if (customFormField.messageKey === 'select_participant' && customFormField.fieldContent) {
        const fieldContent = JSON.parse(customFormField.fieldContent);
        if (!fieldContent.out && !fieldContent.isUse) {
          errorMsg = messages('setting.key620'/* 参与人控件需必选一项 */);// 参与人控件需必选一项
          errorMessageKey = customFormField.messageKey;
          isOk = false;
        }
      }
      if (form.formType === 2001 && ['start_date', 'end_date'].indexOf(customFormField.messageKey) > -1 && !customFormField.required) {
        errorMsg = messages('setting.key2047')/* 开始，结束日期控件须配置为必填 */;
        errorMessageKey = customFormField.messageKey;
        isOk = false;
      }
      if (form.entityType === 1002 && ['start_date', 'end_date'].indexOf(customFormField.messageKey) > -1) {
        startEndDateNum++;
      }
    });

    // 报销单中开始，结束日期需要成对出现
    if (startEndDateNum === 1) {
      errorMsg = messages('setting.key2048')/* 开始，结束日期控件需要一同配置 */;
      isOk = false;
    }

    // 成本中心，加上级联成本中心折算成成本中心，不能超过maxAmount
    if (costCenterMaxAmount && costCenterNum > costCenterMaxAmount) {
      errorMsg = messages('setting.key1656', {arg1: costCenterMaxAmount})/* 成本中心控件只能有{arg1}个 */;
      errorMessageKey = 'select_cost_center';
      isOk = false;
    }

    if (!isOk) {
      message.error(errorMsg);
      errorIndex = this.handleErrorIndex(errorMessageKey);
      if (errorIndex !== -1) {
        this.setState({
          nowSelectedIndex: errorIndex
        });
      }
    }
    return isOk;
  };

  // 预览表单
  handlePreview = () => {
    const { form } = this.handleFormData();
    if (!this.validateData(form)) {
      return;
    }
    const entityType = {
      1001: 'APPLICATION_FORM',
      3001: 'LOAN_BILL',
      1002: 'EXPENSE_CLAIM'
    };
    this.setState({ previewing: true });
    formService.saveTempForm(form).then((res) => {
      this.timeCount = 0;
      this.setState({ previewing: false, qrcodeValue: `helios://preview?appCode=${entityType[res.data.entityType]}&formOID=${res.data.formOID}&formType=${res.data.formType}`}, () => {
        this.interval = setInterval(() => {
          this.timeCount++;
          if (this.timeCount > 30) {
            this.setState({ qrcodeValue: 'timeout'});
            clearInterval(this.interval);
          }
        }, 60000);
      });
    });
  };

  // 必填，只读，打印，代入报表
  // true默认打印，代入;false默认不打印，不代入;null不允许配置打印，代入报表
  renderShowConfig = (widget) => {
    if (widget) {
      const { adjustScopeList } = this.state;
      const showConfig = {required: true, isReadOnly: true};
      if (widget.isPDFShow !== null && widget.isPDFShow !== undefined) {
        showConfig.isPDFShow = true;
      }
      if (widget.reportShow !== null && widget.reportShow !== undefined) {
        showConfig.reportShow = true;
        widget.reportScopeList = this.renderReportScopeList(widget.reportOrmKey);
      }
      if (widget.ledEnabled !== null && widget.ledEnabled !== undefined) {
        showConfig.ledEnabled = true;
        widget.adjustScopeList = this.renderAdjustScopeList(widget.ledOrmKey);
        widget.adjustScopeListAll = adjustScopeList;
      }
      return showConfig;
    }
  };

  // 渲染每个控件可关联的报表属性
  renderReportScopeList = (reportOrmKey) => {
    const { nowWidget } = this.state;
    const reportScopeList = [];
    const selectedReportScopeList = [];
    nowWidget.map((widget) => {
      if (widget.reportShow && widget.reportOrmKey) {
        selectedReportScopeList.push(widget.reportOrmKey);
      }
    });
    this.state.reportScopeList.map((item) => {
      if (selectedReportScopeList.indexOf(item.value) == -1 || item.value === reportOrmKey) {
        reportScopeList.push(item);
      }
    });
    return reportScopeList;
  };

  // 渲染每个控件可参与核算的字段属性
  renderAdjustScopeList = (ledOrmKey) => {
    const { nowWidget, adjustScopeList: adjustScopeListAll } = this.state;
    const adjustScopeList = [];
    const selectedAdjustScopeList = [];
    nowWidget.map((widget) => {
      if (widget.ledEnabled && widget.ledOrmKey) {
        selectedAdjustScopeList.push(widget.ledOrmKey);
      }
      if (widget.messageKey === 'linkage_cost_center' && widget.subLedEnabled && widget.subLedOrmKey) {
        selectedAdjustScopeList.push(widget.subLedOrmKey);
      }
    });
    adjustScopeListAll.map((item) => {
      if (selectedAdjustScopeList.indexOf(item.id) == -1 || item.id === ledOrmKey) {
        adjustScopeList.push(item);
      }
    });
    return adjustScopeList;
  };

  renderWidgetArea = () => {
    // 账套级表单要隐藏这边
    // 信用借款单不让编辑 只有集团模式下有信用借款单
    const { normalWidget, combineWidget} = this.state;
    const { form } = this.context;
    const { tenantMode } = this.props;
    const { fromType } = this.context.form;
    if ((!tenantMode && fromType === 2) || (tenantMode && form.visibleLoanTypeScope === 1004)) {
      return (
        <Col span={4}>
          <div>
          </div>
        </Col>
      );
    }
    return (
      <Col span={8}>
        <div className="widget-area">
          <div className="widget-category">{messages('setting.key621'/* 普通控件 */)}</div>
          <div className="widget-list">
            {normalWidget.map((widget) => (
              <DragWidgetItem widget={widget}
                                                          key={widget.messageKey} />
            ))}
          </div>
          <div className="widget-category">{messages('setting.key622'/* 组合控件 */)}</div>
          <div className="widget-list">
            {combineWidget.map((widget) => (
              <DragWidgetItem widget={widget}
                                                           key={widget.messageKey} />
            ))}
          </div>
        </div>
      </Col>
    );

  };

  // 预览表单二维码
  renderPreviewQCode = () => {
    const { previewing, qrcodeValue } = this.state;
    return (
      <Spin spinning={previewing}>
        {qrcodeValue
          ? (
            <div style={qrcodeValue === 'timeout' ? {position: "relative", opacity: 0.5} : {}}>
              <QrCode
              value={qrcodeValue}
              renderAs="svg"
              fgColor="#000000"
              size={160}
            />
              {qrcodeValue === 'timeout' && <div className="qrcode-timeout">二维码已过期</div>}
            </div>
          )
          : "预览失败"}
        <div style={{textAlign: "center"}}>{qrcodeValue === 'timeout' ? messages('setting.key1989')/* 请重新点击预览 */ : messages('setting.key1990')/* 请使用汇联易扫码预览 */}</div>
      </Spin>
    );
  };

  changeSwitchStatus = (checked) => {
    // console.log(checked, this.state.nowSelectedIndex, this.state.nowWidget)
   if (!checked) {
    // let { nowWidget, nowSelectedIndex } = this.state;
    // nowWidget.splice(nowSelectedIndex, 1);
    // this.setState({ nowWidget, nowSelectedIndex: -1 });
    // this.handleDelete(this.state.nowSelectedIndex)
    if (!this.props.tenantMode) {
      return;
    } else {
      let { nowWidget, nowSelectedIndex } = this.state;
      nowWidget.splice(nowSelectedIndex, 1);
      if (nowWidget.length > 0) {
        nowSelectedIndex = 0;
      }
      this.setState({ nowWidget, nowSelectedIndex });
    }
   }
    // this.setState({
    //   nowWidget: newarr
    // })
  }

  render() {
    const {
      normalWidget, combineWidget, nowWidget, nowSelectedIndex, loading, formDescriptionWidget, saving
    } = this.state;
    const selectedWidget = nowSelectedIndex === -1 ? formDescriptionWidget : nowWidget[nowSelectedIndex];
    const { tenantMode } = this.props;
    const { form } = this.context;
    return (
      <div className="drag-widget-page form-detail-custom">
        {loading ? <Spin /> : (
          <div>
            <FakeDropLayout />
            <Row gutter={40}>
              {
                  this.renderWidgetArea()
                }
              <Col span={8}>
                <IPhoneX type="iPhoneX" title={form.formName}>
                  <PhoneContent
                    widgetList={nowWidget}
                    formDescriptionWidget={formDescriptionWidget}
                    onSort={this.handleSort}
                    deleteEnabled={this.context.form.fromType != 2 || this.props.tenantMode}
                    dragEnabled={this.context.form.fromType != 2 || this.props.tenantMode}
                    nowSelectedIndex={nowSelectedIndex}
                    onDelete={this.handleDelete}
                    onSelect={this.handleSelectWidget}
                    onDrop={this.handleDrop}
                    changeSwitchStatus={this.changeSwitchStatus}
                  />
                </IPhoneX>
              </Col>
              <Col span={8} className="form-detail-custom-setting">
                <WidgetSetting
                  widget={selectedWidget}
                  isFormDesign
                  formType={this.context.formType}
                  formOID={this.context.formOID}
                  booksID={this.context.booksID}
                  needType
                  nowWidgetList={nowWidget}
                  showConfig={this.renderShowConfig(selectedWidget)}
                  disabled={!this.props.tenantMode && this.context.form.fromType === 2}
                  valueKey="counterFlag"
                  widgetList={normalWidget.concat(combineWidget)}
                  onChange={this.handleChangeWidget}
                />
                <div className="operate-area">
                  {(tenantMode || this.context.form.fromType !== 2) && (form.visibleLoanTypeScope !== 1004) && (
                    <Button type="primary" loading={saving} onClick={this.handleSave}>{messages('common.save')/* 保存 */}</Button>
                  )}
                  <Popover
                    content={this.renderPreviewQCode()}
                    trigger="click"
                    placement="bottomRight"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                  >
                    <Button type="primary" style={{marginLeft: 12}} onClick={this.handlePreview}>{messages('setting.key1498')/* 预览 */}</Button>
                  </Popover>
                </div>
              </Col>
            </Row>
          </div>
        )}
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    language: state.main.language,
    languageList: state.login.languageList,
    isOldCompany: state.login.isOldCompany,
    user: state.login.user,
    tenantMode: state.main.tenantMode
  };
}

FormDetailCustom.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  booksID: React.PropTypes.string,
  form: React.PropTypes.object,
  propertyList: React.PropTypes.array
};

export default connect(mapStateToProps)(withDragDropContext(FormDetailCustom));
